//查询数据
function getData(url) {
    let flag = new Array();
    $.ajax({
            type: 'POST',
            async: false,
            url: preUrl + url,
            data: {
                pageSize: 100000,
            }
        })
        .done(function(res) {
            if (res.code == 100) {

                flag = res.object;
            } else {
                layer.msg(res.extend.msg);
                flag = false;
            }
        })
    return flag;
}



function checkPage(i, obj) {
    for (let j in obj) {
        if (i == j) {
            return obj[j];
        }
    }
}


//返回当前页字典对象
function checkCurPage() {
    var keyStr = window.location.href.split("home/")[1].split(".html")[0];
    switch (keyStr) {
        case "product":
            return productKey;
            break;
        case "user":
            return userKey;
            break;
        case "orderList":
            return orderKey;
            break;
        case "productType":
            return productTypeKey;
            break;
        case "discount":
            return discountKey;
            break;
        case "check":
            return checkKey;
            break;
        case "comment":
            return commentKey;
            break;
        case "percentage":
            return percentageKey;
            break;
        case "integration":
            return interKey;
            break;
        case "voucher":
             return voucherKey;
            break;
        case "yearEnd":
            return yearEndKey;
            break;
        default:
            break;
            
    };

}


//翻译当前页字段含义
function translateName(i) {
    var keyStr = window.location.href.split("home/")[1].split(".html")[0];
    switch (keyStr) {
        case "product":
            return checkPage(i, productKey);
            break;
        case "user":
            return checkPage(i, userKey);
            break;
        case "productType":
            return checkPage(i, productTypeKey);
            break;
        case "orderList":
            return checkPage(i, orderKey);
            break;
        case "discount":
            return checkPage(i, discountKey);
            break;
        case "check":
            return checkPage(i, checkKey);
            break;
        case "comment":
            return checkPage(i, commentKey);
            break;
        case "percentage":
             return checkPage(i, percentageKey);
            break;
        case "integration":
             return checkPage(i, interKey);
            break;
        case "voucher":
             return checkPage(i, voucherKey);
            break;
        case "yearEnd":
             return checkPage(i, yearEndKey);
            break;
        default:
            break;
    };

}

function returnFormText(fName, type) {
    switch (type) {
        case "text":
            return "<div class='layui-form-item'><label class='layui-form-label'>" + translateName(fName) + "</label><div class='layui-input-block'><input type='text' name='" + fName + "'  lay-verify='required' autocomplete='off' placeholder='请输入' class='layui-input'></div></div>";
            break;
        case "radio":
            return "<div class='layui-form-item'><label class='layui-form-label'>" + translateName(fName) + "</label><div class='layui-input-block'><input type='radio' name='" + fName + "'  value='1' title='是'  ><input type='radio' name='" + fName + "' value='0' title='否' checked=''> </div></div>";
            break;
        case "file":
            return "<div class='layui-form-item'><label class='layui-form-label'>" + translateName(fName) + "</label><div class='layui-input-block'><div class='layui-btn layui-btn-normal'>上传" + translateName(fName) + "</div><input multiple type='file' name='" + fName + "' class='uploadBtn' /></div></div>";
            break;
        default:
            break;
    }
}



function returnFormType(fName) {

    if (TextKey.indexOf(fName) > -1) {
        return returnFormText(fName, "text");
    } else if (CheckboxKey.indexOf(fName) > -1) {
        return returnFormText(fName, "radio");
    } else if (FileKey.indexOf(fName) > -1) {
        return returnFormText(fName, "file");
    }
}

function add(url) {
    $(".addForm").html("");
    // var cont = "<div class='layui-form addForm'>";
    for (let i in checkCurPage()) {

        $(".addForm").append($(returnFormType(i)));
    }
    // cont+="</div>"
    $(".addForm").css("padding-top", "30px");
    $(".addForm").css("background-color", "#f2f2f2");
    var submit = $("<div class='layui-form-item'><label class='layui-form-label'></label><div class='layui-input-block'><button class='layui-btn' lay-submit='' lay-filter='formDemo'>立即提交</button><button type='reset' class='layui-btn layui-btn-primary cancelAdd'>取消</button></div></div>");
    $(".addForm").append(submit);
    $(".addForm").show();
    // var index = layer.open({
    //     type:1,
    //     area:['80%', '100%'],
    //     title:"新增数据",
    //     content:$(".addForm"),
    // });

    layui.use(['table', 'form', 'upload'], function() {
        var form = layui.form;
        var upload = layui.upload;
        var table = layui.table;

        //监听提交
        form.on('submit(formDemo)', function(data) {
            var index = layer.load(0, {
                shade: [0.2, '#000'] //0.1透明度的白色背景
            });

            $(".addForm").hide();
            var formData = new FormData();

            for (let j in data.field) {
                formData.append(j, data.field[j]);
            }
            $.ajax({
                    type: 'POST',
                    async: false,
                    url: preUrl + url,
                    contentType: false,
                    processData: false,
                    data: formData
                })
                .done(function(res) {
                    if (res.code == 100) {

                        layer.msg("添加成功");

                    } else {
                        layer.msg(res.extend.msg);

                    }
                })

        });
        var table = layui.table
        form.render();

    })



}


function detail(data) {
    // $(".addForm").html("");
    // console.log(data)
    //  var cont = "<div class='layui-form addForm'>";
    $(".addForm").html("");
    for (let i in data) {
        var item = $("<div style='line-height:45px;padding-left:200px;'>" + translateName(i) + ":" + data[i] + "</div>");
        $(".addForm").append(item);
    }
    var button = $("<button style='margin-left:200px;' class='clear layui-btn layui-btn-md'>关闭</button>");
    $(".addForm").prepend(button);

    $(".addForm").css("padding-top", "10px");
    $(".addForm").css("background-color", "#F2F2F2");
    $(".addForm").show();
    layui.use(['table', 'form', 'upload'], function() {
        var form = layui.form;
        var upload = layui.upload;
        var table = layui.table;
        var table = layui.table
        form.render();

    })

}
//审核
function checkUser(url,formdata) {
    let index = layer.load(0, { shade: [0.3, "#000"] });
    $.ajax({
            type: 'POST',
            url: preUrl + url,
            processData: false,
            contentType: false,
            data: formdata
        })
        .done(function(res) {
            layer.close(index);
            if (res.code == 100) {
                layer.msg("处理成功")
                obj.del();
            } else {
                layer.msg(res.extend.msg);

            }
        })
}


//删除 
function delData(url, formdata, obj) {
    let index = layer.load(0, { shade: [0.3, "#000"] });
    $.ajax({
            type: 'POST',
            url: preUrl + url,
            processData: false,
            contentType: false,
            data: formdata
        })
        .done(function(res) {
            layer.close(index);
            if (res.code == 100) {
                layer.msg("删除成功")
                obj.del();
            } else {
                layer.msg(res.extend.msg);

            }
        })
}

function changeData(url, data) {
    let index = layer.load(0, { shade: [0.3, "#000"] });
    $.ajax({
            type: 'POST',
            url: preUrl + url,
            processData: false,
            contentType: false,
            data: data
        })
        .done(function(res) {
            layer.close(index);
            if (res.code == 100) {
                layer.msg("修改成功")

            } else {
                layer.msg(res.extend.msg);

            }
        })
}

$(".addForm").on("click", ".clear", function() {
    $(this).parent().html("");
    $(this).parent().hide();
})

$(".addForm").on("click", ".cancelAdd", function() {
    $(".addForm").html("");
    $(".addForm").hide();
})

//追加JSOn表格到对象obj
function initJsonArray(arr, obj) {

    let newArr = new Array();
    let preObj = {
        fixed: 'left',
        type: 'checkbox'
    };
    let laterObj = {
        fixed: 'right',
        title: '操作',
        toolbar: '#barDemo2'
    };
    newArr.push(preObj);
    for (let i in arr[0]) {
        let objItem = new Object();
        objItem.field = i;
        objItem.title = translateName(i);
        objItem.sort = true;
        objItem.edit = "text";
        if (i.toLowerCase().indexOf('id') > -1) {

            objItem.title = i;
            delete objItem.edit;

        }
        if (i.indexOf('typeCode') > -1) {

            objItem.title = i;
            delete objItem.edit;

        }
        newArr.push(objItem);
    }
    newArr.push(laterObj);
    var finalArr = new Array();
    finalArr.push(newArr);
    layui.use(['table', 'form'], function() {
        var form = layui.form;
        var table = layui.table;
        layui.table.render({
            elem: obj,
            cellMinWidth: 170,
            title: '数据表',
            page: true,
            limit: 10,
            cols: finalArr,
            data: arr

        });
        table.on('tool()', function(obj) {

            var data = obj.data;
            var form = new FormData();
            if (obj.event === 'mynormal') {
                var userNumber = obj.data.userNumber;
                mynormalList(userNumber);
            } else if (obj.event === 'delproductType') {
                form.append("productTypeId", form, obj);
                delData("/productType/delete", form, obj)
            }
        });
    })


}

//合伙人列表
function partnerList(userNumber) {
    let index = layer.load(0, { shade: [0.3, "#000"] });
    var form = new FormData();
    form.append("userNumber", userNumber);
    $.ajax({
            async: false,
            url: preUrl + '/user/partnerList',
            type: 'POST',
            "processData": false,
            "contentType": false,
            data: form,

        })
        .done(function(res) {
            layer.close(index);
            if (res.code == 100) {
                let list = res.object;
                initJsonArray(list, "#test2")
                $(".formlist").show();

                layer.open({
                    type: 1,
                    title: "数据表格",
                    maxmin: true,
                    toolbar: '#mytoolbar1',
                    skin: 'layui-layer-molv',
                    area: ["100%", "100%"],
                    content: $(".formlist"),
                    cancel: function() {
                        $(".formlist").hide();
                    }
                })

            } else {
                layer.msg(res.extend.msg);
            }
        })

}

//合伙人列表
function mynormalList(userNumber) {
    let index = layer.load(0, { shade: [0.3, "#000"] });
    var form = new FormData();
    form.append("userNumber", userNumber);
    $.ajax({
            async: false,
            url: preUrl + '/user/mynormalList',
            type: 'POST',
            "processData": false,
            "contentType": false,
            data: form,

        })
        .done(function(res) {
            layer.close(index);
            if (res.code == 100) {
                let list = res.object;

                initJsonArray(list, "#test3")
                $(".formlist1").show();

                layer.open({
                    type: 1,
                    title: "数据表格",
                    maxmin: true,
                    skin: 'layui-layer-molv',
                    area: ["100%", "100%"],
                    content: $(".formlist1"),
                    cancel: function() {
                        $("#test3").html("");
                    }
                })

            } else {
                layer.msg(res.extend.msg);
            }
        })

}

//二级类型列表
function listtwo(productTypeId) {
    let index = layer.load(0, { shade: [0.3, "#000"] });
    var form = new FormData();
    form.append("productTypeId", productTypeId);
    $.ajax({
            async: false,
            url: preUrl + '/productType/listtwo',
            type: 'POST',
            "processData": false,
            "contentType": false,
            data: form,

        })
        .done(function(res) {
            layer.close(index);
            if (res.code == 100) {
                let list = res.object;

                initJsonArray(list, "#test4")
                $(".formlist1").show();

                layer.open({
                    type: 1,
                    title: "数据表格",
                    maxmin: true,
                    skin: 'layui-layer-molv',
                    area: ["100%", "100%"],
                    content: $(".formlist1"),
                    cancel: function() {
                        $("#test4").html("");
                        $("#test4").parent().hide();
                    }
                })

            } else {
                layer.msg(res.extend.msg);
            }
        })

}

function initTable(url) {
    let data = getData(url);
    if (!data) {
        return false;
    }
    let newArr = new Array();
    let preObj = {
        fixed: 'left',
        type: 'checkbox'
    };
    let laterObj = {
        fixed: 'right',
        title: '操作',
        toolbar: '#barDemo'
    };


    newArr.push(preObj);
    for (let i in data[0]) {
        let objItem = new Object();
        objItem.field = i;

        objItem.title = translateName(i);
        objItem.sort = true;
        objItem.edit = "text";

        if (i.toLowerCase().indexOf('id') > -1) {
            objItem.title = i;
            delete objItem.edit;

        }
        if (i.indexOf('typeCode') > -1) {

            delete objItem.edit;

        }
        newArr.push(objItem);
    }
    newArr.push(laterObj);
    var finalArr = new Array();
    finalArr.push(newArr);
    layui.use(['table', 'form'], function() {
        var form = layui.form;
        var table = layui.table;
        layui.table.render({
            elem: '#test',
            toolbar: '#mytoolbar',
            cellMinWidth: 170,
            url: preUrl + url,
            method: "POST",
            title: '数据表',
            request: {
                limitName: 'pageSize',
            },
            response: {
                statusName: 'code',
                statusCode: 100,
                dataName: 'object'
            },
            page: true,
            limit:10,
            cols: finalArr,
            // data: data

        });
        //监听单元格编辑
        table.on('edit', function(obj) {

            var value = obj.value,
                data = obj.data,
                field = obj.field; //得到字段
            var formdata = new FormData();
            if (url == "/product/list") {
                formdata.append("productId", obj.data.productId);
                formdata.append(field, value);
                changeData("/product/update", formdata);
            } else if (url.indexOf("productType") > -1) {
                formdata.append("productTypeId", obj.data.productTypeId);
                formdata.append(field, value);
                changeData("/productType/update", formdata);
            } else if (url.indexOf("order/list") > -1) {
                
                formdata.append("orderId", obj.data.orderId);
                formdata.append(field, value);
                changeData("/productType/update", formdata);
            }else if (url.indexOf("productDiscount") > -1) {
                formdata.append("discountId", obj.data.discountId);
                formdata.append(field, value);
                changeData("/productDiscount/update", formdata);
            }
            else if (url.indexOf("percentage") > -1) {
                formdata.append("percentageId", obj.data.percentageId);
                formdata.append(field, value);
                changeData("/percentage/update", formdata);
            }
             else if (url.indexOf("conversion") > -1) {
                formdata.append("conversionId", obj.data.conversionId);
                formdata.append(field, value);
                changeData("/conversion/update",formdata);
            }
            else if (url.indexOf("voucher") > -1) {
                formdata.append("voucherId", obj.data.voucherId);
                formdata.append(field, value);
                changeData("/voucher/update",formdata);
            }
             else if (url.indexOf("yearEnd") > -1) {
                formdata.append("yearId", obj.data.yearId);
                formdata.append(field, value);
                changeData("/yearEnd/update",formdata);
            }

        });
        table.on('addData', function(obj) {

            var value = obj.value,
                data = obj.data,
                field = obj.field; //得到字段

        });

        //监听行工具事件
        table.on('tool()', function(obj) {

            var data = obj.data;
            console.log(obj);
            if (obj.event == 'del') {
                layer.confirm('真的删除么', function(index) {

                    layer.close(index);
                    if (url == "/product/list") {
                        var data = new FormData();
                        data.append("productId", obj.data.productId);
                        delData("/product/delete", data, obj);
                    } else if (url.indexOf("productType") > -1) {
                        var data = new FormData();
                        data.append("productTypeId", obj.data.productTypeId);
                        delData("/productType/delete", data, obj);
                    } else if (url.indexOf("order/list") > -1) {
                        var data = new FormData();
                        data.append("orderId", obj.data.orderId);
                        delData("/order/api/delete", data, obj);
                    }else if (url.indexOf("productDiscount") > -1) {
                        var data = new FormData();
                        data.append("discountId", obj.data.discountId);
                        delData("/productDiscount/delete", data, obj);
                    }
                    else if (url.indexOf("percentage") > -1) {
                        var data = new FormData();
                        data.append("percentageId", obj.data.percentageId);
                        delData("/percentage/delete",JSON.stringify(data), obj);
                    }
                    else if (url.indexOf("conversion") > -1) {
                        var data = new FormData();
                        data.append("conversionId", obj.data.conversionId);
                        delData("/conversion/delete",data, obj);
                    }
                     else if (url.indexOf("voucher") > -1) {
                        var data = new FormData();
                        data.append("voucherId", obj.data.voucherId);
                        delData("/voucher/delete",data, obj);
                    }
                });
            } else if (obj.event == 'edit') {
                layer.msg("单击单元格修改..");
            } else if (obj.event == 'detail') {
                detail(obj.data);
            } else if (obj.event === 'partnerList') {
                var userNumber = obj.data.userNumber;
                partnerList(userNumber);

            } else if (obj.event == 'mynormal') {
                var userNumber = obj.data.userNumber;
                mynormalList(userNumber);
            } else if (obj.event == 'listtwo') {

                var productTypeId = obj.data.productTypeId;
                listtwo(productTypeId);
            }else if(obj.event == 'refuse'){
              
                // checkUser(userId,1);
            }else if(obj.event == 'pass'){
                 var userId = obj.data.userId;
                 var data=new FormData();
                 data.append("userId",userId);
                 data.append("userAccount",2);
                    checkUser("/user/partnerUpdate",data);
            }
        });
    });








}